<template>
  <div class="container">
    <div class="app-container">
      <!-- 左 -->
      <div class="left">
        <el-input v-model="queryParams.keyword" style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small" placeholder="输入员工姓名全员搜索" @input="onSearch" />
        <!-- 树形组件 -->
        <el-tree
          ref="treeRef"
          :data="depts"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          highlight-current
          @current-change="change"
        /></div>
      <!-- 右 -->
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="space-between">
          <el-button size="mini" @click="sendMultiMessage">群发通知</el-button>
          <el-row>
            <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
            <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
            <el-button size="mini" @click="emplolyee">excel导出</el-button>
          </el-row>

        </el-row>
        <!-- 表格组件 -->
        <el-table
          ref="employeeTable"
          row-key="id"
          :data="EmployeeData"
          style="width: 100%"
          :default-sort="{prop: 'date', order: 'descending'}"
          @select="selectChange"
          @select-all="selectChange"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column
            prop="staffPhoto"
            label="头像"
          >
            <template #default="{row}">
              <img v-if="row.staffPhoto" :src="row.staffPhoto" class="user-avatar" style="width:30px;height:30px">
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            sortable
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            sortable
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            :formatter="formOf"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable
          />
          <el-table-column
            label="操作"
            width="280px"
          >
            <template #default="{row}">
              <el-button type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                style="margin-left: 8px;"
                @onConfirm="confirmDel(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>

        </el-table>
        <!-- 分页 -->
        <div style="text-align:center;margin-top:10px">
          <el-pagination
            background
            layout="prev, pager, next,total"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            @current-change="handleCurrentChange"
          />
        </div>

      </div>
      <importExcel :show-excel-dialog.sync="showExcelDialog" @uploadFile="getDepartment" />

      <el-dialog :visible.sync="showRoleDialog" title="分配角色" @close="btnRes">
        <!-- 弹层内容 -->
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">
            {{ role.name }}
          </el-checkbox>
        </el-checkbox-group>
        <div style="text-align:center;margin-top:20px">
          <el-button type="primary" @click="btnOk">确定</el-button>
          <el-button @click="btnRes">取消</el-button>
        </div>
      </el-dialog>
      <el-dialog title="群发通知" :visible.sync="showMultiMessageDialog">
        <div class="select_users">
          <el-tag
            v-for="item in all_users"
            :key="item.id"
            closable
            @close="delSendUser(item)"
          >@{{ item.username }}</el-tag>
        </div>
        <el-form label-width="80px">
          <el-form-item label="消息等级">
            <el-select v-model="messageForm.type" size="mini">
              <el-option :value="1" label="通知消息" />
              <el-option :value="2" label="提示消息" />
              <el-option :value="3" label="重要消息" />
              <el-option :value="4" label="紧急消息" />

            </el-select>
          </el-form-item>
          <el-form-item label="通知内容">
            <el-input v-model="messageForm.content" type="textarea" :rows="4" place-holder="通知内容的长度在5-100个字符" />
          </el-form-item>
        </el-form>

        <!-- 群发通知 -->
        <template #footer>
          <el-row type="flex" justify="end">
            <el-button size="mini" @click="btnCancelSend">取消</el-button>
            <el-button size="mini" type="primary" @click="btnSendMultiMessage">发送通知</el-button>
          </el-row>
        </template>

      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getDepartmentApi } from '@/api/department'
import { delemployeeApi, exportEmployee, getEmployeeDetailApi, getEmpolyeeApi, sendMultiMessageAPI } from '@/api/employee'
import { transObjToTree } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
import { assignRoleApi, getEnableRoleListApi } from '@/api/role'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      showMultiMessageDialog: false,
      selectUsers: {},
      depts: [],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      messageForm: {
        type: 1, // 1 通知消息 2 提示消息 3  重要消息 4 紧急消息
        content: ''
      },
      total: null,
      showExcelDialog: false,
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      EmployeeData: [],
      showRoleDialog: false, // 用来控制角色弹层的显示
      roleList: [], // 接收角色列表
      roleIds: [], // 用来双向绑定数据的
      currentUserId: null
    }
  },
  computed: {
    all_users() {
      return [...Object.values(this.selectUsers).flat()]
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    delSendUser(item) {
      // item哪一页的？？？？
      // 删除selectUser中的数据
      // 页面上取消勾选
      Object.keys(this.selectUsers).forEach(key => {
        const index = this.selectUsers[key].findIndex(row => row.id === item.id)
        if (index > -1) {
          this.selectUsers[key].splice(index, 1) // 删除存储的数据
          this.$refs.employeeTable.toggleRowSelection(item, false) // 页面上取消勾选
        }
      }) // [1,2,3,4,5...]
    },
    // 群发消息
    sendMultiMessage() {
      if (!this.all_users.length) {
        return this.$message.warning('请先选择要群发的员工')
      }
      this.showMultiMessageDialog = true
    },
    // 选择发生变化
    selectChange(selectRows) {
      // 去重
      this.selectUsers = {
        ...this.selectUsers,
        [this.queryParams.page]: selectRows
      }
    },
    btnCancelSend() {
      this.showMultiMessageDialog = false
    },
    // 发送消息
    async btnSendMultiMessage() {
      if (!this.all_users.length) {
        return this.$message.warning('发送的用户不能为空')
      }
      if (!this.messageForm.content) {
        return this.$message.warning('消息内容不能为空')
      }
      await sendMultiMessageAPI({
        userIds: this.all_users.map(item => item.id), // [{ id: 11 }]  //[1,2,3,4,4]
        ...this.messageForm // type content
      })
      this.$message.success('群发消息成功')
      this.messageForm = {
        type: 1,
        content: ''
      }
      this.showMultiMessageDialog = false
    },
    async btnOk() {
      await assignRoleApi(
        {
          id: this.currentUserId,
          roleIds: this.roleIds
        }
      )
      this.$message.success('分配用户角色成功')
      this.btnRes()
    },
    btnRes() {
      this.roleIds = []
      this.showRoleDialog = false
    },
    async btnRole(id) {
      this.currentUserId = id
      this.roleList = await getEnableRoleListApi()
      const { roleIds } = await getEmployeeDetailApi(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async getDepartment() {
      const res = await getDepartmentApi()
      this.depts = transObjToTree(res, 0)
      this.queryParams.departmentId = this.depts[0].id

      this.$nextTick(() => {
        this.$refs.treeRef.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    change(data) {
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const res = await getEmpolyeeApi(this.queryParams)
      this.total = res.total
      this.EmployeeData = res.rows
    },
    formOf(row) {
      const user = {
        1: '正式',
        2: '非正式'
      }
      return user[row.formOfEmployment]
    },
    async handleCurrentChange(page) {
      this.queryParams.page = page
      await this.getEmployeeList()
      // 切换页码处理选中问题
      console.log(this.selectUsers[this.queryParams.page])
      this.$refs.employeeTable.store.states.selection = this.selectUsers[this.queryParams.page] || []
      this.$refs.employeeTable.store.updateSelectionByRowKey() // 重新计算selection
      this.$refs.employeeTable.store.updateAllSelected() // 计算全选
    },
    onSearch() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    async emplolyee() {
      const res = await exportEmployee()
      // FileSaver.saveAs(blob对象,文件名称)
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    async confirmDel(id) {
      await delemployeeApi(id)
      this.$message.success('删除成功')
      if (this.EmployeeData.length === 1 && this.queryParams.pagesize > 1) {
        this.queryParams.page -= 1
      }
      this.getEmployeeList()
    }
  }
}
</script>
<style lang="scss" scoped>
    .app-container {
    background: #fff;
    display: flex;
    .left {
      width: 280px;
      padding: 20px;
      border-right: 1px solid #eaeef4;
    }
    .right {
      flex: 1;
      padding: 20px;
      .opeate-tools {
        margin:10px ;
      }
      .username {
        height: 30px;
        width: 30px;
        line-height: 30px;
        text-align: center;
        border-radius: 50%;
        color: #fff;
        background: #04C9BE;
        font-size: 12px;
        display:inline-block;
      }
    }
  }
  .select_users {
  display: flex;
  flex-wrap: wrap;
  padding: 10px 10px;
  border: 1px solid #ccc;
  border-radius: 10px;
  span {
    margin: 6px 5px;
  }
}

</style>
